<template>
  <Modal
    v-model="showImportTestcaseModal"
    title="导入用例"
    fullscreen
    :mask-closable="false"
    :closable="false"
    @on-cancel="handleImportCancel"
  >
    <div style="display: flex; justify-content: flex-end">
      <Form
        inline
        :label-width="80"
        :model="uploadTestcaseData"
        :rules="uploadTestcaseDataValidate"
      >
        <FormItem label="所属项目" prop="project">
          <Select
            v-model="uploadTestcaseData.project"
            filterable
            style="width: 300px"
          >
            <Option
              v-for="item in projects"
              :value="item.id"
              :key="item.id"
              :label="item.name"
            />
          </Select>
        </FormItem>
        <FormItem :label-width="0">
          <Button
            size="small"
            type="text"
            icon="md-download"
            style="color: #2d8cf0"
            @click="downloadTestcaseTemplate"
          >
            下载模板
          </Button>
        </FormItem>
        <FormItem :label-width="0">
          <Upload
            :before-upload="uploadTestcaseFile"
            action="#"
            accept=".xls,.xlsx"
          >
            <Button
              size="small"
              type="text"
              style="color: #2d8cf0"
              icon="md-cloud-upload"
            >
              文件上传
            </Button>
          </Upload>
        </FormItem>
      </Form>
    </div>
    <div
      style="
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 10px;
      "
    >
      <div v-if="file !== null">
        {{ file.name }}
        <Button
          size="small"
          type="text"
          style="color: #ed4014"
          @click="removeFile"
        >
          删除
        </Button>
      </div>
    </div>
    <Table
      :columns="testcaseColumns"
      :data="uploadTestcaseData.testcase"
      border
      size="small"
      style="margin-top: 10px"
      :tooltip-max-width="500"
    >
      <template slot-scope="{ row, index }" slot="action">
        <Button
          size="small"
          type="text"
          style="color: #ed4014"
          @click="removeTestcase(row, index)"
          >移除</Button
        >
      </template>
    </Table>
    <div slot="footer">
      <Button type="default" @click="handleImportCancel">取消</Button>
      <Button
        type="primary"
        @click="handleImportSubmit"
        :disabled="
          !(
            uploadTestcaseData.project && uploadTestcaseData.testcase.length > 0
          )
        "
        >确定</Button
      >
    </div>
  </Modal>
</template>

<script>
import {
  downloadTestcaseTemplate,
  uploadTestcaseFile,
  batchCreateTestcase,
} from "@/api/HttpAutoTestService/testcase";
import { getProjectNames } from "@/api/HttpAutoTestService/project";

export default {
  name: "testcase-import",
  props: {
    importTestcase: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    showImportTestcaseModal: {
      get() {
        return this.importTestcase;
      },
      set(val) {
        this.$emit("update:importTestcase", val);
      },
    },
  },
  mounted() {
    // 获取项目
    getProjectNames()
      .then((res) => {
        this.projects = res.data;
      })
      .catch((err) => {
        this.$Modal.error({
          title: "系统异常，请联系管理员……",
          content: JSON.stringify(err),
          closable: true,
        });
      });
  },
  data() {
    return {
      testcaseColumns: [
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left",
        },
        {
          title: "用例名称（必填）",
          key: "name",
          width: 350,
          tooltip: true,
          fixed: "left",
        },
        {
          title: "请求URL（必填）",
          key: "url",
          width: 350,
          tooltip: true,
        },
        {
          title: "请求方法",
          key: "method",
          align: "center",
          width: 100,
        },
        {
          title: "Headers参数（选填）",
          key: "headers",
          width: 350,
          align: "center",
          ellipsis: true,
        },
        {
          title: "Body参数类型（选填）",
          key: "request_data_type",
          width: 120,
          align: "center",
        },
        {
          title: "Body参数",
          key: "request_data",
          width: 350,
          align: "center",
          ellipsis: true,
        },
        {
          title: "用例期望结果（选填）",
          key: "expect_result",
          width: 350,
          align: "center",
          ellipsis: true,
        },
        {
          title: "备注",
          key: "remark",
          minWidth: 350,
          tooltip: true,
        },
        {
          title: "操作",
          slot: "action",
          width: 80,
          align: "center",
          fixed: "right",
        },
      ],
      file: null,
      projects: [],
      uploadTestcaseData: {
        project: "",
        testcase: [],
      },
      uploadTestcaseDataValidate: {
        project: [{ required: true, message: "请选择项目", trigger: "change" }],
      },
    };
  },
  methods: {
    removeTestcase(row, index) {
      this.uploadTestcaseData.testcase.splice(index, 1);
      if (this.uploadTestcaseData.testcase.length == 0) {
        this.file = null;
        this.uploadTestcaseData.testcase = [];
      }
    },
    downloadTestcaseTemplate() {
      downloadTestcaseTemplate().then((res) => {
        if (res.status === 200) {
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          const blobUrl = window.URL.createObjectURL(blob);
          const elementLink = document.createElement("a");
          elementLink.download = "批量创建用例模板.xlsx";
          elementLink.style.display = "none";
          elementLink.href = blobUrl;
          // 触发点击
          document.body.appendChild(elementLink);
          elementLink.click();
          // 然后移除
          document.body.removeChild(elementLink);
        }
      });
    },
    uploadTestcaseFile(file) {
      this.file = file;
      let fd = new FormData();
      fd.append("file", this.file);
      uploadTestcaseFile(fd).then((res) => {
        this.uploadTestcaseData.testcase = res.data;
      });
      return false;
    },
    removeFile() {
      this.file = null;
      this.uploadTestcaseData.testcase = [];
    },
    handleImportSubmit() {
      batchCreateTestcase(this.uploadTestcaseData)
        .then((res) => {
          if (res.status === 200) {
            let data = res.data;
            let content =
              "创建新接口：" +
              data.new_api +
              " 个<br/>创建新用例：" +
              data.new_testcase +
              " 个";
            this.$Modal.info({
              title: "创建成功",
              content: content,
              closable: true,
            });
            this.handleImportCancel();
          }
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },
    handleImportCancel() {
      this.showImportTestcaseModal = false;
      this.uploadTestcaseData.project = "";
      this.removeFile();
      this.$emit("initTestcaseTable");
    },
  },
};
</script>

<style scoped>
</style>
